<?php
defined('IN_ECTOUCH') or die('Deny Access');

require_once('WxPayConfig.class.php');
require_once('wechat.class.php');
require_once('WxMoneyConfig.class.php');
require_once('WxMoneyBusConfig.class.php');
require_once('WxMoneyApi.class.php');
//佣金分发
class Wxpay_deliveryController{

	protected $wechat = null;
	protected $DB= null;

	public function __construct() {

		$options = array(
 			// 'token'=>'tokenaccesskey', //填写你设定的key
 			// 'encodingaeskey'=>'encodingaeskey', //填写加密用的EncodingAESKey
 			'appid'=>'XXXXXXXXX', //填写高级调用功能的app id
 			'appsecret'=>'1q11111111111111' //填写高级调用功能的密钥
 		);
 		
		$this->wechat =new Wechat($options);
		$this->DB='ecs_';
	}

	public function admin_logs($mes, $name, $file_name)
	{
		$now_time=time();
		$log_info="(".$file_name."-".$name.')'.$mes;
		$user_id=$_SESSION['user_id']?$_SESSION['user_id']:0;
	    $sql=" insert into ".$this->DB."admin_log(`log_time`,`user_id`,`log_info`) "
	           ." values('$now_time','$user_id','$log_info')";
	    $result1= mysql_query($sql);
	}
     //企业付款调用接口
	 public function busSendProfit($mshop_id,$user_id,$openid,$cash_money=0) {

	 	    $rand_num = rand(0,99999999);
	        $bill_no = sprintf('%010d', $rand_num);
			$mch_billno= WxPayConfig::MCHID.date("Ymd").$bill_no;//自定义订单号

			//佣金取整
			$cash_money=intval($cash_money);

           //记录企业付款
			$result_re=$this->recordBussiness($mshop_id,$user_id,$openid,$cash_money,$mch_billno);

			$re_mch_billno=0;
			$payment_no=0;
			if($result_re)
			{
				 //发送红包
	    		$result =$this->sendMoneyByBus($openid,$cash_money,$mch_billno);//会不会返回的值异步的
	    		 // print_r($result);exit;
	           if($result['result_code'] == 'SUCCESS' ) {
	    			//更新数据库
	    		    $re_mch_billno=$result['partner_trade_no'];	//企业付款 订单号
	    		    $payment_no=$result['payment_no'];	//企业付款微信订单号 			
					$this->updaterecordBus(1,$result['return_msg'],$re_mch_billno,$payment_no);
					return true;
	    		} else {	
	    			//更新数据库，报错
	    			$re_mch_billno=$mch_billno;		
					$this->updaterecordBus(2,$result['return_msg'],$re_mch_billno,$payment_no);
					return false;
	    		}
	    		
			}
			else
				return false;

	 }
	  /**
     * 企业付款
     * @param  [string] $openid [description]
     * @param  [int] $total  [description]
     * @return [array]         [description]
     */
	public function sendMoneyByBus($openid,$total,$mch_billno) {

		//实例化红包设置对象，用于参数设置
		$input = new WxMoneyBusConfig();

		$total=$total*100;//单位分

		//各种参数设置
		$input->setNonce_str(WxMoneyApi::getNonceStr());


		$input->setPartner_trade_no($mch_billno);
		$input->setMchid(WxPayConfig::MCHID);
		$input->setMch_appid(WxPayConfig::APPID);
		$input->setDevice_info('');
		$input->setOpenid($openid);

		$input->setCheck_name('NO_CHECK');
		$input->setRe_user_name('尊敬的中服运动掌柜');
		$input->setAmount($total);


		$input->setSpbill_create_ip('127.0.0.1');

		$input->setDesc('分享越多得越多，中服运动不需囤货得高额佣金！');
		#签名要最后调用，因为需要先设置参数
		$input->setSign();//
		//执行发送红包
		$result = WxMoneyApi::sendBus($input);

		// $this->printf_info($result);
		// var_dump($result);
		return $result;
	}



	   /**
     * 记录数据
     * @param  [type] $mshop_id       [description]
     * @param  [type] $user_id    [description]
     * @param  [type] $openid   [description]
     * @param  [type] $total_fee    [description]
     */
    public function recordBussiness($mshop_id,$user_id,$openid,$pay_fee,$mch_billno) {


        $row=$this->paylogInfo($mch_billno);
      
       if(!$row)
       {
	       	$now_time=time();
	       	$total_fee=$pay_fee;//企业付款金额限制小

	       	

	         //插入提现记录
	        $sql="insert  into " . $this->DB."mshop_pay_log(`mshop_id`,`user_id`,`openid`,"
	        	 ."`pay_fee`,`total_fee`,`status`,`ctime`,`mch_billno`)"
	             ." values('$mshop_id','$user_id','$openid','$pay_fee','$total_fee','0','$now_time','$mch_billno')";
	        $result1= mysql_query($sql);
	        if($result1)
	        {
	 	         //减少可提现金额
		        $sql=" update " . $this->DB."mshop set sum_profit=(sum_profit-$pay_fee),lock_profit=(lock_profit+$pay_fee)"
		               ." where mshop_id='$mshop_id'";
		        $result2= mysql_query($sql);       	
	        }


	        if($result1&&$result2)
	        {
	            $mes='记录成功，自定义订单号'.$mch_billno.",会员".$user_id.",提现".$pay_fee."元。";
			    /* 记录管理员操作 */
			    $this->admin_logs($mes, 'record', 'Wxpay_delivery');
	        	return true;
	        }
	        else
	        {

	            $mes='记录失败，自定义订单号'.$mch_billno.",会员".$user_id.",提现".$pay_fee."元。";
			    /* 记录管理员操作 */
			     $this->admin_logs($mes, 'record', 'Wxpay_delivery');
	        	return false;
	        }
       }
       else
       {
       	return false;
       }
        
    }

 /**
     * 更新数据2,$result['return_msg']$re_mch_billno,$payment_no
     * @param  [type] $updaterecord    [description] status=1 红包发送成功，status=2 红包发送失败
     */
    public function updaterecordBus($status,$remark="",$mch_billno,$payment_no) {
    	$row=$this->paylogInfo($mch_billno);
    	$now_time=time();
        if($row)
        {
       	   $mshop_id=$row['mshop_id'];
       	   $pay_fee=$row['pay_fee'];
       	   $user_id=$row['user_id'];
	       	  //减少可提现金额,累加已提现佣金
	        $result1=0;
	        if($status==1)//付款成功
	        {


	            //确认提现记录
		        $sql=" update " . $this->DB."mshop_pay_log set status='$status',pay_time='$now_time',pay_no=$payment_no where mch_billno='$mch_billno'";
		        $result1= mysql_query($sql); 
		        if($result1)
		        {
		          $sql=" update " . $this->DB."mshop set sum_cash_amount=(sum_cash_amount+'$pay_fee'),"
	               ." lock_profit=(lock_profit-$pay_fee) "
	               ." where mshop_id='$mshop_id'";
	               $result2= mysql_query($sql);  
	                $mes='提现成功，记录成功，微信付款单号'.$payment_no.",会员".$user_id.",提现".$pay_fee."元";
		        }
		        else
		        {
		        	$mes='提现成功，记录失败，微信付款单号'.$payment_no.",会员".$user_id.",提现".$pay_fee."元";
		        }

		        
			    /* 记录管理员操作 */
			     $this->admin_logs($mes, 'updaterecord', 'Wxpay_delivery');
	        	return true;	
	        }
	        elseif($status==2)
	        {
	         //错误释放锁定佣金
                
	        	//确认提现记录
		        $sql=" update " . $this->DB."mshop_pay_log set status='$status',pay_time='$now_time',remark='$remark' where mch_billno='$mch_billno'";
		        $result1= mysql_query($sql); 


	           if($result1)
		        {
		          $sql=" update " . $this->DB."mshop set sum_profit=(sum_profit+'$pay_fee'),"
	               ." lock_profit=(lock_profit-$pay_fee) "
	               ." where mshop_id='$mshop_id'";
	               $result2= mysql_query($sql);  
	               $mes='提现失败，自定义订单号'.$mch_billno.",会员".$user_id.",提现".$pay_fee."元";
		        }
		        else
		        {
		        	$mes='提现失败，记录失败，自定义订单号'.$mch_billno.",会员".$user_id.",提现".$pay_fee."元";
		        }
			    /* 记录管理员操作 */
			     $this->admin_logs($mes, 'updaterecord', 'Wxpay_delivery');
	        	return false;
	        }
	        
       }
       else
       {
        	return false;
       }
        
       
    }


	
    /**
     * 检测是否有发送记录
     * @return boolean [description]
     */
    public function paylogInfo($mch_billno) {

        $sql=" select * from " .$this->DB."mshop_pay_log where status=0 and mch_billno='$mch_billno'";
        $row=mysql_fetch_array(mysql_query($sql));
        if($row)//检测是否有领取记录
        {
        	return $row;
        }
        else
        {
        	return false;
        }
    	

    }

 public function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
  }

	/**
	 * 格式化打印输出
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function printf_info($data){
	  foreach($data as $key=>$value){
	      echo "<font color='#00ff55;'>$key</font> : $value <br/>";
	  }
	}





}